/* 
 * Created on 2007-4-22
 * Last modified on 2007-4-22
 * Powered by YeQiangWei.com
 */
package com.yeqiangwei.image;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import com.yeqiangwei.util.Validator;
import com.yeqiangwei.util.ArithHelper;

public class ImageJpeg extends ImageOperate{
	
	private static final Logger logger = Logger.getLogger(ImageJpeg.class);

	
	public static void main(String[] args){
		String p = "C:/Documents and Settings/Administrator/My Documents/My Pictures/a.jpg";
		String f = "C:/Documents and Settings/Administrator/My Documents/My Pictures/a_.jpg";
		ImageOperate img = new ImageJpeg();
		boolean bea = img.narrowOrEnlarge(p,f,0,300);
		System.out.println(bea);
	}
	
	public boolean clip(BufferedInputStream bis, String filePathAndName, int w, int h, int x, int y, int x_w, int y_h) {
    	boolean bea = false;
        int ow = 0; /*指定的尺寸不在计算中变化*/
        int oh = 0; /*指定的尺寸不在计算中变化*/
        int x_ = x_w+x;
        int y_ = y_h+y;
		if(!com.yeqiangwei.util.Validator.isEmpty(bis)){
			try {
				Image img = javax.imageio.ImageIO.read(bis);
				ow = img.getWidth(null);
				oh = img.getHeight(null);
				/* 判断指定的坐标是否越界 */
				if(ow < x+x_w){
					x_ = ow;
					x = x_ - x_w;
				}
				if(oh < y_){
					y_ = oh;
					y = y_ - y_h;
				}
				if(x_-x > ow || y_-y > oh){
					x=0;
					y=0;
					x_=ow;
					y_=oh;
				}
				java.awt.image.BufferedImage tag = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
	            Graphics g = tag.getGraphics();
	            g.drawImage(img, 0, 0, w, h, x, y, x_, y_, null);
	            FileOutputStream out = new FileOutputStream(new File(filePathAndName)); /* 输出到文件流 */  
	            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
	            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);   
	            param.setQuality(1.0F,true);   
	            encoder.encode(tag); /*JPEG编码*/ 
	            out.flush();
	            out.close();
	            out = null;
	            bea = true;
			} catch (IOException e) {
				logger.error(e.toString());
			}
		}
		return bea;
	}

	public boolean clip(String path, String filePathAndName, int w, int h, int x, int y, int x_w, int y_h) {
		return super.clip(path,filePathAndName,w,h,x,y,x_w,y_h);
	}
	
	public boolean incise(File file, String filePathAndName, int w, int h
    		, int x, int y, int x_w, int y_h){
		boolean bea = false;
        int ow = 0; /*指定的尺寸不在计算中变化*/
        int oh = 0; /*指定的尺寸不在计算中变化*/
        int x_ = x_w+x;
        int y_ = y_h+y;
		try{ 
			Image img = javax.imageio.ImageIO.read(file);
			ow = img.getWidth(null);
			oh = img.getHeight(null);
			/* 判断指定的坐标是否越界 */
			if(ow < x+x_w){
				x_ = ow;
				x = x_ - x_w;
			}
			if(oh < y_){
				y_ = oh;
				y = y_ - y_h;
			}
			if(x_-x > ow || y_-y > oh){
				x=0;
				y=0;
				x_=ow;
				y_=oh;
			}
			java.awt.image.BufferedImage tag = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, w, h, x, y, x_, y_, null);
            FileOutputStream out = new FileOutputStream(filePathAndName); //输出到文件流  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);   
            param.setQuality(0.99F,true);
            com.sun.image.codec.jpeg.JPEGQTable qta = param.getQTable(0);   
            param.setQTable(1,qta.getScaledInstance(1.0F,true));   
            encoder.setJPEGEncodeParam(param);
            encoder.encode(tag); /*JPEG编码*/ 
            out.flush();
            out.close();
            out = null;
            g = null;
            tag = null;
            bea = true;
		}catch(Exception e){ 
			logger.error(e.toString());
		}	

		return bea;
	}

	@Override
	public boolean narrowOrEnlarge(String opath, String npath, int w, int h) {
    	if(Validator.isEmpty(opath)||Validator.isEmpty(npath)){
    		return false;
    	}
    	boolean bea = false;
        final int ow = w; //指定的尺寸不在计算中变化
        final int oh = h; //指定的尺寸不在计算中变化
        double wd = 0;
        double hd = 0;
        String ws = "", hs = "";
		try {
	        Image img = javax.imageio.ImageIO.read(new File(opath));
			int width = img.getWidth(null); //得到源图宽  
	        int height = img.getHeight(null); //得到源图长
	        if(width==-1 || height==-1){
	        	return false;
	        }
            //同时指定宽高
            if(w > width){
                w = width;
            }
            if(h > height){
                h = height;
            }  
            if(w>0 && w < width && h==0){
                // 计算出宽度的缩放比例
                wd = ArithHelper.div(w, width, 10);     
                hd = ArithHelper.mul(wd, height);
                hd = ArithHelper.round(hd,0); //四舍五入保留小数点0位
                hs = String.valueOf(hd).substring(0, String.valueOf(hd).indexOf("."));
                h = Integer.parseInt(hs) ; //按比例缩小高度
                if(h<1){
                    h = height;
                }
            }
            else if(h > 0 && h < height && w==0){
            	hd = ArithHelper.div(h,height,10);
                wd = ArithHelper.mul(hd,width);
                wd = ArithHelper.round(wd,0); //四舍五入保留小数点0位
                ws = String.valueOf(wd).substring(0, String.valueOf(wd).indexOf("."));
                w = Integer.parseInt(ws) ; //按比例缩小高度
                if(w<1){
                    w = width;
                }
            }
            else if(w>0 && h>0){
            	//计算出宽度的缩放比例
                wd = ArithHelper.div(ow, width, 10);     
                hd = ArithHelper.mul(wd, height);
                hd = ArithHelper.round(hd,0); //四舍五入保留小数点0位
                hs = String.valueOf(hd).substring(0, String.valueOf(hd).indexOf("."));
                h = Integer.parseInt(hs) ; //按比例缩小高度
                if(h<1){
                    h = height;
                }
                if(h<oh){//如果指定小图的比例不符合原图的比例
                	h = oh;
                	hd = ArithHelper.div(oh, height, 10);     
                    wd = ArithHelper.mul(hd, width);
                    wd = ArithHelper.round(wd,0); //四舍五入保留小数点0位
                    ws = String.valueOf(wd).substring(0, String.valueOf(wd).indexOf("."));
                    w = Integer.parseInt(ws) ; //按比例缩小高度
                    if(w<1){
                        w = width;
                    }
                }
            }
            /*
            System.out.println("w:"+w);
            System.out.println("h:"+h);
            System.out.println("ow:"+ow);
            System.out.println("oh:"+oh);
            */
            java.awt.image.BufferedImage tag = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
            Graphics g = tag.getGraphics();
            if(w>0 && h>0){
                g.drawImage(img, 0, 0, w, h, 0, 0, width, height, null);
             }else{
                g.drawImage(img, 0, 0, w, h, null);
            }
            FileOutputStream out = new FileOutputStream(npath); /* 输出到文件流 */  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);   
            param.setQuality(1.0F,true);
            //com.sun.image.codec.jpeg.JPEGQTable qta = param.getQTable(0);   
            //param.setQTable(1,qta.getScaledInstance(1.0F,true));   
            encoder.setJPEGEncodeParam(param);
            encoder.encode(tag); /*JPEG编码*/ 
            out.flush();
            out.close(); 
            bea = true;
		} catch (IOException e) {
			logger.debug(e.toString());
		}
		return bea;
	}

	@Override
	public boolean watermark(String opath, String npath, String wpath){
		Image image = null;;
		try {
			image = javax.imageio.ImageIO.read(new File(opath));
		} catch (IOException e) {
			logger.error(e.toString());
		}
		if(Validator.isEmpty(image)){
			return false;
		}
		return this.watermark(image,opath,npath,wpath);
	}
	
	@Override
	public boolean watermark(String opath, String npath, String wpath, int minwidth, int minheight) {
		Image image = null;
		try {
			image = javax.imageio.ImageIO.read(new File(opath));
			if(image.getWidth(null)<minwidth||image.getHeight(null)<minheight){
				return false;
			}else{
				return this.watermark(image,opath,npath,wpath);
			}
		} catch (IOException e) {
			logger.error(e.toString());
		}
		return false;
	}
	
	private boolean watermark(Image image, String opath, String npath, String wpath) {
		try {
			//Image src = javax.imageio.ImageIO.read(new File(opath));
			int w = image.getWidth(null); /* 得到源图宽 */  
	        int h = image.getHeight(null); /* 得到源图高 */
	        if(w==-1||h==-1){
	        	return false;
	        }
	        Graphics gim = image.getGraphics();
	        BufferedImage tag = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
	        tag.getGraphics().drawImage(image,0,0,w,h,null);
            Image img1 = javax.imageio.ImageIO.read(new File(wpath));//构造Image对象 
            int w1 = img1.getWidth(null); /* 得到水图1宽 */  
            int h1 = img1.getHeight(null); /* 得到水图1高 */
            //img1 = img1.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH);
            tag.getGraphics().drawImage(img1,w-w1-12,h-h1-5,w1,h1,null);
            FileOutputStream out=new FileOutputStream(npath); //输出到文件流  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);   
            param.setQuality(0.90F,true);
            com.sun.image.codec.jpeg.JPEGQTable qta = param.getQTable(0);   
            param.setQTable(1,qta.getScaledInstance(1.0F,true));   
            encoder.setJPEGEncodeParam(param);
            encoder.encode(tag); //JPEG编码 
            gim.dispose();
            out.close();   
		} catch (IOException e) {
			logger.error(e.toString());
		} 
		return false;
	}
}
